package ar.com.pragmatia.lanacion;

import java.io.File;
import java.util.UUID;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import ar.com.pragmatia.lanacion.data.PendingClient;

public class NewClientActivity extends LaNacionActivity {

	private Button btnAddClient;
	private Button btnAdditional1;
	private Button btnAdditional2;
	private EditText txtShopName;
	private EditText txtBusinessName;
	private EditText txtClientName;
	private EditText txtLegalCertificate;
	private EditText txtShopPhone;
	private EditText txtAddress;
	private Spinner spnPrices;
	private PendingClient client;
	private Button btnTakePicture;

	private Dialog dialog;
	private Context appContext;
	private UUID unique;

	// private LocationListener locationListener;
	private LocationListener locationListener2;
	private LocationManager locationManager;
	private int trys;
	private ProgressDialog progressDialog;

	private ImageView imageView;
	private Bitmap imageBitmap;
	private String tmpImage;
	private final int CAMERA_PIC_REQUEST = 1337;

	private OnClickListener takeFoto = new OnClickListener() {

		public void onClick(View v) {
			Intent cameraIntent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			File imageDirectory = new File((new File(tmpImage)).getParent());
			String path = imageDirectory.toString().toLowerCase();
			// String name = imageDirectory.getName().toLowerCase();

			ContentValues values = new ContentValues();
			values.put(Media.TITLE, "Image");
			values.put(Images.Media.BUCKET_ID, path.hashCode());
			// values.put(Images.Media.BUCKET_DISPLAY_NAME, name);

			values.put(Images.Media.MIME_TYPE, "image/jpeg");
			// values.put(Media.DESCRIPTION, "Image capture by camera");
			values.put("_data", tmpImage);
			Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
					values);
			cameraIntent
					.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
			cameraIntent.putExtra(
					android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST) {
			final int THUMBNAIL_HEIGHT = 200;

			imageBitmap = BitmapFactory.decodeFile(tmpImage);
			Float width = new Float(imageBitmap.getWidth());
			Float height = new Float(imageBitmap.getHeight());
			Float ratio = width / height;
			imageBitmap = Bitmap.createScaledBitmap(imageBitmap,
					(int) (THUMBNAIL_HEIGHT * ratio), THUMBNAIL_HEIGHT, false);

			imageView.setImageBitmap(imageBitmap);

			// try {
			// HttpFileUploader htfu = new HttpFileUploader(
			// "http://192.168.1.157/test.php");
			// BasicNameValuePair newVar = new BasicNameValuePair("test",
			// "hola!");
			// htfu.addVar(newVar);
			// htfu.addFile("/sdcard/Parki/test.jpg", "laFoto.jpg",
			// "uploadedfile");
			// new Thread(htfu).start();
			// } catch (FileNotFoundException e1) {
			// e1.printStackTrace();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.clients_new);

		Button btnClients = (Button) findViewById(R.id.btnClients);
		if (btnClients != null) {
			btnClients.setPressed(true);
		}

		if (client == null) {
			client = new PendingClient();
		}

		unique = UUID.randomUUID();
		tmpImage = "/sdcard/LaNacion/Client/" + unique + ".jpg";
		txtShopName = (EditText) findViewById(R.id.txtShopName);
		txtBusinessName = (EditText) findViewById(R.id.txtBusinessName);
		txtClientName = (EditText) findViewById(R.id.txtClientName);
		txtShopPhone = (EditText) findViewById(R.id.txtShopPhone);
		txtLegalCertificate = (EditText) findViewById(R.id.txtLegalCertificate);
		txtAddress = (EditText) findViewById(R.id.txtAddress);

		btnTakePicture = (Button) findViewById(R.id.btnTakePicture);

		btnTakePicture.setOnClickListener(takeFoto);

		imageView = (ImageView) findViewById(R.id.photoResultView);

		// txtObservations = (EditText) findViewById(R.id.txtObservations);
		// txtRegistryNumber = (EditText) findViewById(R.id.txtRegistryNumber);
		// txtAuthorizedId = (EditText) findViewById(R.id.txtAuthorizedId);

		spnPrices = (Spinner) findViewById(R.id.spnPrices);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.clients_prices_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnPrices.setAdapter(adapter);

		appContext = this;

		btnAddClient = (Button) findViewById(R.id.btnAddClient);

		btnAdditional1 = (Button) findViewById(R.id.btnAdditional1);

		btnAdditional2 = (Button) findViewById(R.id.btnAdditional2);

		OnClickListener addClient = new OnClickListener() {

			public void onClick(View v) {
				locationManager = (LocationManager) appContext
						.getSystemService(Context.LOCATION_SERVICE);
				trys = 0;
				progressDialog = ProgressDialog.show(NewClientActivity.this,
						getString(R.string.wait), getString(R.string.loading),
						true, false);
				// Define a listener that responds to location updates
				// locationListener = new LocationListener() {
				// public void onLocationChanged(Location location) {
				// // Called when a new location is found by the network
				// // location provider.
				// makeUseOfNewLocation(location);
				// }
				//
				// public void onStatusChanged(String provider, int status,
				// Bundle extras) {
				// }
				//
				// public void onProviderEnabled(String provider) {
				// }
				//
				// public void onProviderDisabled(String provider) {
				// }
				// };
				locationListener2 = new LocationListener() {
					public void onLocationChanged(Location location) {
						// Called when a new location is found by the network
						// location provider.
						makeUseOfNewLocation(location);
					}

					public void onStatusChanged(String provider, int status,
							Bundle extras) {
					}

					public void onProviderEnabled(String provider) {
					}

					public void onProviderDisabled(String provider) {
					}
				};

				// Register the listener with the Location Manager to receive
				// location updates
				// locationManager.requestLocationUpdates(
				// LocationManager.NETWORK_PROVIDER, 300, 0,
				// locationListener);
				locationManager
						.requestLocationUpdates(LocationManager.GPS_PROVIDER,
								300, 0, locationListener2);
			}

		};

		btnAddClient.setOnClickListener(addClient);

		OnClickListener additional1Listener = new OnClickListener() {

			public void onClick(View v) {
				dialog = new Dialog(appContext);
				dialog.setContentView(R.layout.dialog_additional1);
				dialog.setTitle("Additional 1");

				if (client != null) {
					if (client.getGiro() != null) {
						EditText giro = (EditText) dialog
								.findViewById(R.id.txtGiro);
						giro.setText(client.getGiro());
					}
					if (client.getRegistryNumber() != null) {
						EditText registryNumber = (EditText) dialog
								.findViewById(R.id.txtRegistryNumber);
						registryNumber.setText(client.getRegistryNumber());
					}
					if (client.getAuthorizedSigner() != null) {
						EditText authorizedSigner = (EditText) dialog
								.findViewById(R.id.txtAuthSigner);
						authorizedSigner.setText(client.getAuthorizedSigner());
					}
					if (client.getAuthorizedSignerIdCard() != null) {
						EditText authorizedSignerIdCard = (EditText) dialog
								.findViewById(R.id.txtAuthorizatedIdSigner);
						authorizedSignerIdCard.setText(client
								.getAuthorizedSignerIdCard());
					}
				}

				Button cancel = (Button) dialog.findViewById(R.id.btnCancel);
				cancel.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						dialog.dismiss();

					}
				});
				Button save = (Button) dialog.findViewById(R.id.btnSave);
				save.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						if (client != null) {

							EditText giro = (EditText) dialog
									.findViewById(R.id.txtGiro);
							EditText registryNumber = (EditText) dialog
									.findViewById(R.id.txtRegistryNumber);
							EditText authorizedSigner = (EditText) dialog
									.findViewById(R.id.txtAuthSigner);
							EditText authorizedSignerIdCard = (EditText) dialog
									.findViewById(R.id.txtAuthorizatedIdSigner);

							if (!giro.getText().toString().isEmpty()) {
								client.setGiro(giro.getText().toString());
							}
							if (!registryNumber.getText().toString().isEmpty()) {
								client.setRegistryNumber(registryNumber
										.getText().toString());
							}
							if (!authorizedSigner.getText().toString()
									.isEmpty()) {
								client.setAuthorizedSigner(authorizedSigner
										.getText().toString());
							}
							if (!authorizedSignerIdCard.getText().toString()
									.isEmpty()) {
								client.setAuthorizedSignerIdCard(authorizedSignerIdCard
										.getText().toString());
							}
						}
						dialog.dismiss();

					}
				});
				dialog.show();
			}

		};

		btnAdditional1.setOnClickListener(additional1Listener);

		OnClickListener additional2Listener = new OnClickListener() {

			public void onClick(View v) {
				dialog = new Dialog(appContext);
				dialog.setContentView(R.layout.dialog_additional2);
				dialog.setTitle("Additional 2");

				if (client != null) {
					if (client.getCity() != null) {
						EditText city = (EditText) dialog
								.findViewById(R.id.txtCity);
						city.setText(client.getCity());
					}
					if (client.getState() != null) {
						EditText state = (EditText) dialog
								.findViewById(R.id.txtState);
						state.setText(client.getState());
					}
				}

				Button cancel = (Button) dialog.findViewById(R.id.btnCancel);
				cancel.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						dialog.dismiss();

					}
				});
				Button save = (Button) dialog.findViewById(R.id.btnSave);
				save.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						if (client != null) {

							EditText city = (EditText) dialog
									.findViewById(R.id.txtCity);
							EditText state = (EditText) dialog
									.findViewById(R.id.txtState);

							if (!city.getText().toString().isEmpty()) {
								client.setCity(city.getText().toString());
							}
							if (!state.getText().toString().isEmpty()) {
								client.setState(state.getText().toString());
							}
						}
						dialog.dismiss();

					}
				});
				dialog.show();
			}

		};
		btnAdditional2.setOnClickListener(additional2Listener);

	}

	private void makeUseOfNewLocation(Location l) {
		if (l.getAccuracy() < 10 || trys >= 10) {
			locationManager.removeUpdates(locationListener2);
			progressDialog.dismiss();

			client = createClientFromFields();
			client.setLocation("(" + l.getLatitude() + ", " + l.getLongitude()
					+ ")");
			if (client.save()) {
				String text = getText(R.string.client_added).toString();
				int duration = Toast.LENGTH_SHORT * 2;
				Toast toast = Toast.makeText(getApplicationContext(), text,
						duration);
				toast.show();
				Intent index = new Intent().setClass(appContext,
						MainClientActivity.class);
				startActivity(index);
			}
		}
		trys++;

	}

	private PendingClient createClientFromFields() {
		if (client != null) {
			client.setShopName(txtShopName.getText().toString());
			client.setBusinessName(txtBusinessName.getText().toString());
			client.setClientName(txtClientName.getText().toString());
			client.setTelephone(txtShopPhone.getText().toString());
			client.setLegalCertificate(txtLegalCertificate.getText().toString());
			client.setAddress(txtAddress.getText().toString());
			client.setPrices(spnPrices.getSelectedItem().toString());
			client.setUuid(unique.toString());
		}
		return client;
	}

}
